package randomdata;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class GetIp {
	
	//ip��ַ���в�����λ�ģ�����ǰ�油��
	private static String zeroadd(String orgin) {
		String[] array = orgin.split("\\.");
		StringBuffer ret = new StringBuffer();
		for (String str: array) {
			if (str.length() == 3) {
				ret.append(str);
			} else if (str.length() == 2) {
				ret.append("0" + str);
			} else {
				ret.append("00" + str);
			}
		}
		
		return ret.toString();
	}
	
	public static String  getServerIp(){
		String SERVER_IP=null;
		try {
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;

			while (netInterfaces.hasMoreElements()) {
				boolean flag = false;
				NetworkInterface ni = (NetworkInterface) netInterfaces
						.nextElement();
				//�ж� �ӿ������в���������
				if(!ni.getName().contains(":")){
					Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();   
					while (inetAddresses.hasMoreElements()) {   
			               ip = inetAddresses.nextElement(); 
			               //!ip.isSiteLocalAddress()    �ж���Ϣ�Ƿ�Դ�Ա�����ip
			               if (!ip.isLoopbackAddress()&& ip.getHostAddress().indexOf(":") == -1) {
			            	   SERVER_IP = ip.getHostAddress();
			            	   flag = true;
			            	   break;
			               } else {
			            	   ip = null;
			               }  
					}
				}
			 
				if(flag){
					break;
			    }
			}
		} catch (Exception e) {
			System.err.println("unknown host" + e);
		}
		System.out.println(SERVER_IP);
		return zeroadd(SERVER_IP);
	}
}
